package com.smp.controller;

import com.smp.common.BaseVo;
import com.smp.entry.DocBean;
import com.smp.service.IElasticService;
import com.smp.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: xiaoyu.fang
 * @date: 2020/8/13
 * @version: v1.0
 * @description:
 **/
@Slf4j
@RestController
@RequestMapping("/elastic")
public class ElasticController {

    @Autowired
    private IElasticService elasticService;

    @GetMapping("/init")
    public BaseVo init() {
        List<DocBean> list = new ArrayList<>();
        list.add(new DocBean("XX0193", "XX8064", 1, "张三"));
        list.add(new DocBean("XX0210", "XX7475", 1, "李四"));
        list.add(new DocBean("XX0257", "XX8097", 1, "王五"));
        elasticService.saveAll(list);
        return new BaseVo();
    }

    @GetMapping("/all")
    public BaseVo all() {
        return new BaseVo(elasticService.findAll());
    }

    @GetMapping("/getByContent")
    public BaseVo page(@RequestParam("content") String content) {
        return new BaseVo(elasticService.findByContent(content));
    }

    @PostMapping("/findByFirstCode")
    public BaseVo findByFirstCode(@RequestBody Map<String, Object> params) {
        return new BaseVo(new PageInfo(elasticService.findByFirstCode(params.get("firstCode").toString())));
    }

    /**
     * 查询、高亮
     *
     * @param docBean
     * @return
     */
    @PostMapping("/query")
    public BaseVo query(@RequestBody DocBean docBean) {
        SearchHits<DocBean> docBeanSearchHits = elasticService.query(docBean);
        List<DocBean> docBeans = new ArrayList<>(docBeanSearchHits.getSearchHits().size());
        for (SearchHit<DocBean> searchHit : docBeanSearchHits) {
            // 高亮的内容
            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
            // 将高亮的内容填充到content中
            searchHit.getContent().setContent(highlightFields.get("content") == null ? searchHit.getContent().getName() : highlightFields.get("content").get(0));
            docBeans.add(searchHit.getContent());
        }
        return new BaseVo(docBeans);
    }

}
